#!/usr/bin/perl -T
# babel.pl
use warnings;
# lack of strict
 

use CGI qw(:standard *table);
use locale;
use IO::File;
use POSIX;
use WWW::Babelfish;
use Locale::Language;

if (cookie('name')) {
   my $name = cookie('name');
   my $language = cookie('lang');

   print header, start_html(-bgcolor => 'white', -title => "Reporting");
   setlocale(LC_TIME, cookie('locale'));
   # If it does not exist, defaults to local
   if (!param('report')) {   #Show form
      my ($sec, $min, $hour, $mday, $mon, $year, $wday) = localtime (time);
      print h2(ucfirst(getMessage('hello', $language)),
      " $name,", getMessage("today's date is", $language),
      strftime("%c", $sec, $min, $hour, $mday, $mon, $year, $wday), "\n");
      
      print start_table({bgcolor => 'lightblue', cellspacing => 0,
                         cellpadding => 5}),
      start_form,
      Tr(td([ucfirst(getMessage('report', $language)) ,
      textarea(-rows => 10,
               -columns => 50,
               -name => 'report')])), "\n",
      Tr(td({colspan => 2, align => 'center'},
            submit(ucfirst(getMessage('send', $language))))),
      end_form, end_table;
   } else {   # process it and show it in English
      print h2(ucfirst(getMessage('received', $language)),
      getMessage('report', $language),
      getMessage('by', $language), " $name"),
      p(b("Original"), param('report')),
      p(em (translate(param('report'), code2language($language))));
   }
   } else {   # ask login
   print redirect(-uri => '/cgi-bin/form.pl');
}
print end_html;
sub getMessage {
   my ($key,$language) = @_;
   chomp ($key,$language);
   my $filename = 'messages.txt';
   my $counter = -1;

   my $fh = new IO::File;
   $fh->open("< $filename") or die "Can't open '$filename': $!\n";

   my (@messages,@final);
   while (<$fh>) {
      @messages = (split ', ');
      push @final, @messages;
   }

   chomp @final;

   foreach (@final){
      my $msg;
      $counter++;

      if($_ =~ /$key/ and $language =~ /es/){
         $msg = $final[$counter+1];
         return $msg;
      }
      elsif ($_ =~ /$key/ and $language =~ /fr/) {
         $msg = $final[$counter+2];
         return $msg;
      }
      elsif ($_ =~ /$key/ and $language =~ /en/) {
         $msg = $final[$counter];
         return $msg;
      }
      else {
         next;
      }
   }
}
sub translate {
   my ($toTranslate, $language) = @_;
   my $tr = new WWW::Babelfish() || return $toTranslate;
   my $translated = $tr->translate('source' => $language,
                           'destination' => 'Spanish',
                           'text' => $toTranslate);
   print $language, " ", $tr->error if $tr->error;
   $translated = $toTranslate unless defined ($translated);
   return $translated;
}
